package com.xx.sg.controller;

import com.xx.sg.sso.SsoRequestUtil;
import com.xx.sg.sso.SysUser;
import com.xx.sg.util.SaCheckTicketResult;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @GetMapping("/loginUser")
    @Tag(name = "获取登录用户", description = "获取登录用户")
    public Map loginUser(
            String ticket,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        System.out.println("ticket:" + ticket);
        SysUser user = SsoRequestUtil.getSysUser(ticket,request);

        Map<String, Object> res = new HashMap<>();
        res.put("success", true);
        res.put("code", 200);
        res.put("message", "成功");
        res.put("data", user);
        return res;
    }

    @RequestMapping("/login")
    @Tag(name = "登录", description = "登录")
    public Map login(
            String ticket,
            @RequestParam(defaultValue = "/") String back,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        System.out.println("ticket:" + ticket);

        /*
         * 此时有两种情况:
         * 情况1：ticket无值，说明此请求是Client端访问，需要重定向至SSO认证中心
         * 情况2：ticket有值，说明此请求从SSO认证中心重定向而来，需要根据ticket进行登录
         */
        if (ticket == null) {
            String currUrl = request.getRequestURL().toString();
            String clientLoginUrl = currUrl + "?back=" + SsoRequestUtil.encodeUrl("http://ev5034053yp.vicp.fun/login");
            String serverAuthUrl = SsoRequestUtil.buildServerAuthUrl(clientLoginUrl);
            response.sendRedirect(serverAuthUrl);

        } else {
            // 根据 ticket 登录上
            SaCheckTicketResult ctr = SsoRequestUtil.checkTicket(ticket, request, "/login");

            // 返回 back 地址
            response.sendRedirect(back);
        }

        Map<String, Object> res = new HashMap<>();
        res.put("success", true);
        res.put("code", 200);
        res.put("message", "成功");
        res.put("data", "regionSituation");
        return res;
    }


    /**
     * SpringBoot3 好像默认不提供 favicon.ico 路由了，每次访问时都会在控制台报错，挺烦人的，
     * 所以这里提供一个空的 favicon.ico 路由
     * @return /
     */
    @GetMapping("/favicon.ico")
    public String favicon() {
        return "no favicon";
    }
}
